package com.store.view.basic;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.store.application.Product;
import com.store.application.Store;
import com.store.view.SpringContext;

/**
 * Servlet implementation class GestionFormServlet
 */
public class ListOfProductsServlet extends HttpServlet {
	
	Store store;
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListOfProductsServlet() {
        super();
        ApplicationContext context = SpringContext.getApplicationContext();
        store =  (Store)context.getBean("store");
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		List<Product> products = store.getListOfProducts();
		request.setAttribute("products", products);
		request.getRequestDispatcher("JSP/basic/listOfProducts.jsp").forward(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String order = request.getParameter("order");
		if(order.equals("order now")){
			
			List<Product> productsToOrder = new ArrayList<Product>();
			
			List<Product> products = store.getListOfProducts();
			Product product;
			
			for(int i=0; i<products.size(); i++){
				product = products.get(i);
				int identifier = product.getId();
				String id = request.getParameter("productID" + (i+1));
				if(id != null){
					if(identifier == Integer.parseInt(id)){
						productsToOrder.add(product);
					}
				}
			}
			
			int orderIdentifier = store.order(productsToOrder);
			
			response.sendRedirect("/venteEnLigne/editCustomerProfile?orderIdentifier=" + orderIdentifier);
		}
	
			
	}

}
